package com.mrobuy.jdvc.controller;

import com.mrobuy.jdvc.entity.VCProductApply;
import com.mrobuy.jdvc.service.ShelvesItemService;
import com.mrobuy.util.Pagination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
public class ShelvesItemController {

	private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd_HHmmss");

	@Autowired
	private ShelvesItemService shelvesItemService;

	@RequestMapping("shelves/applies")
	public String applies(Model model) {
		return "shelves/applies";
	}

	@RequestMapping("shelves/priceexport")
	public String priceexport(Model model) {
		return "shelves/priceexport";
	}

	@RequestMapping("shelves/publishexport")
	public String publishexport(Model model) {
		return "shelves/publishexport";
	}

	@RequestMapping("shelves/epexport")
	public String epexport(Model model) {
		return "shelves/epexport";
	}

	/**
	 * 商品申请列表查询
	 */
	@RequestMapping("shelves/apply/query")
	@ResponseBody
	public Object applyquery(HttpServletRequest request, VCProductApply condition) {

		int start = ServletRequestUtils.getIntParameter(request, "start", 1);
		int length = ServletRequestUtils.getIntParameter(request, "length", 100);
		int draw = ServletRequestUtils.getIntParameter(request, "draw", 1);

		Pagination pagination = shelvesItemService.loadApplies(start, length, condition);

		pagination.setDraw(draw);

		return pagination;
	}


	/**
	 * 申请商品价格文件导出
	 */
	@RequestMapping("shelves/apply/priceexport")
	@ResponseBody
	public void attrExport(HttpServletRequest request, HttpServletResponse response) {

		try {
			response.setContentType("application/vnd.ms-excel");
			String fileName = "帷易胜价格_wysgyp_" + DATE_FORMAT.format(new Date()) + ".xlsx";
			String userAgent = request.getHeader("User-Agent");
			if(StringUtils.contains(userAgent, "Firefox")){//火狐浏览器
				fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
			}else{//IE，google等其他浏览器
				fileName = URLEncoder.encode(fileName,"UTF8");
			}
			response.setHeader("Content-disposition", "attachment;filename=" + fileName);
			OutputStream ouputStream = response.getOutputStream();
			shelvesItemService.priceexport(ouputStream);
			ouputStream.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}



}
